import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import moment from 'moment';
import { Input, Select, Checkbox,Radio,Modal, Form, Button, message, Spin,Row, Col, Table, InputNumber } from 'antd';

const FormItem = Form.Item;
const { Option } = Select;

export default class Index extends Component{

  state={
    selectedIds:[],
    deliverWay:1,
    listNum:[],
    selectedListNum:[],
    foot:{footer:null},
    ItemList:[],
    required:true
  }

  componentDidMount(){
    window.Isoption = true;
    const {list,addressListLoading, expressListLoading} = this.props;
    const { listNum } = this.state;
    let arr=[];
    list&&list.forEach(item=>{
      arr.push({OrderId:item.OrderId,ExpressId:item.ExpressId,WaybillNumber:''});
    })
    this.setState({
        ItemList:arr,
    })
    console.log(arr)
    //let obj=addressListLoading&&expressListLoading?{footer:null}:{};
  }

  componentWillMount() {
    window.Isoption = false;
  }

	okHandle = () => {
    const {form,comfirm,list} = this.props;
    const { selectedIds ,listNum,selectedListNum,ItemList} = this.state;
    //if(!selectedIds.length) return message.error('未选择发货商品');
    form.validateFieldsAndScroll((err, values) =>{
      if(!values.storeAddressId) return;
      if(values.deliverWay==1){
        for(let i=0;i<list.length;i++){
          if(!values[`Express${i}`]){
            return;
          }
          if(!values[`billNumber${i}`]){
            return;
          }
        }
      }else{
        for(let i=0;i<list.length;i++){
           ItemList.push({OrderId:list[i].OrderId,ExpressId:0,WaybillNumber:''});
        }
      }
      let params={
        storeAddressId:values.storeAddressId,
        ItemList:ItemList
      };
      console.log(params)
      if(typeof comfirm === 'function') comfirm(params);
    });
  }


  handleModalVisible = () => {
    const { handleModalVisible } =this.props;
    if(typeof handleModalVisible === 'function') handleModalVisible();
  }

  changeDeliverWay = (e) =>{
    const {form:{setFieldsValue},list} = this.props;
    this.setState({
      deliverWay:e.target.value,
      required:e.target.value==1?true:false
    },()=>{
      list.forEach((v,i)=>{
        setFieldsValue({
          ['billNumber' + (() => i)()]:"",
          ['Express' + (() => i)()]:"",
        })
      })
      this.forceUpdate();
    })
  }

  changeDeliverNum = (e,record,index) => {
    const { ItemList} = this.state;
    const {list} = this.props;
    console.log(e)
    if(!ItemList.length){
        let arr=[];
        list&&list.forEach(item=>{
            arr.push({OrderId:item.OrderId,ExpressId:item.ExpressId,WaybillNumber:''});
          })
        arr[index].WaybillNumber=e.target.value;
        this.setState({
            ItemList:arr
        })
    }else{
        ItemList[index].WaybillNumber=e.target.value;
        this.setState({
            ItemList
        })
    }

  }

  selectExpress = (e,index)=>{
    const { ItemList} = this.state;
    const {list} = this.props;
    if(!ItemList.length){
        let arr=[];
        list&&list.forEach(item=>{
            arr.push({OrderId:item.OrderId,ExpressId:item.ExpressId,WaybillNumber:''});
        })
        arr[index].ExpressId=e;
        this.setState({
            ItemList:arr
        })
    }else{
        ItemList[index].ExpressId=e;
        this.setState({
            ItemList
        })
    }

  }

	render(){
    const {modalVisible,form:{getFieldDecorator},addressList,expressList,list,confirmLoading,addressListLoading,expressListLoading,allLoading} = this.props;
    const {selectedIds,deliverWay,listNum,foot,required} = this.state;
    const columns = [
      {
        title: '收货人',
        dataIndex: 'ReceiveName',
        width:'20%',
        render: val=>(<div className="xkd-text-ellipsis" style={{width:100}} title={val}><span >{val}</span></div>)
      },
      {
        title: '订单号',
        dataIndex: 'OrderNo',
        width: '25%',
      },
      {
        title: '物流公司',
        dataIndex: 'ExpressId',
        width: '28%',
        render:(val,record,index)=>(
            <FormItem >
            {getFieldDecorator('Express'+index,{
              rules:[
                {required:required,message:'请选择物流公司'}
              ],
              validateTrigger:'onBlur'
            })(
              <Select style={{ width: '100%' }} onChange={(e)=>this.selectExpress(e,index)} disabled={deliverWay==2}>
                {expressList &&

              expressList.map(item => {
                      return <Option value={item.Id} key={item.Id}>{item.Name}</Option>;
                  })}
              </Select>
            )}
          </FormItem>
          )
      },
      {
        title: '快递单号',
        dataIndex: 'WaybillNumber',
        width: '27%',
        render:(text,record,index) =>(
          <FormItem >
            {getFieldDecorator('billNumber'+index,{
              rules:[
                {required:required,message:'请填写快递单号'}
              ],
              validateTrigger:'onBlur'
            })(
              <Input   onChange={(e)=>this.changeDeliverNum(e,record,index)} disabled={deliverWay==2}/>
            )}
          </FormItem>
        )
      },
    ];

    const rowSelection = {
      selectedRowKeys: selectedIds,
      onChange: (selectedIds, selectedRows) => {
        const {listNum,selectedListNum} = this.state;
        const { list } = this.props;
        console.log(selectedIds, selectedRows)
        let arr=[];
        selectedIds.forEach((v)=>{
          let index= list.OrderItem.findIndex(item=>item.Id==v);
          arr.push(listNum[index])
        })
        this.setState({
          selectedIds: selectedIds,
          selectedListNum:arr,
        });
      },
    };
    let obj=addressListLoading||expressListLoading?foot:{}
		 return (
      <Modal
        destroyOnClose
        centered
        title="批量发货"
        visible={modalVisible}
        onOk={this.okHandle}
        confirmLoading={ confirmLoading }
        onCancel={this.handleModalVisible}
        width={640}
        {...obj}
        className={`${styles.deliverModal}`}
      >
          <Spin spinning={addressListLoading||expressListLoading}>
          <div>
                <Row className={styles.deliverWay}>
                    <Col span={12}>
                        <FormItem
                            labelCol={{ span: 6 }}
                            wrapperCol={{ span: 18 }}
                            label="发货方式"
                        >
                            {getFieldDecorator('deliverWay',{
                            initialValue:1
                            })(
                            <Radio.Group  style={{width:'100%'}} onChange={this.changeDeliverWay} >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item style={{marginBottom:0}}>
                                            <Radio value={1}>需要物流</Radio>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12} >
                                        <Form.Item style={{marginBottom:0}}>
                                            <Radio value={2}>无需物流</Radio>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Radio.Group>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem
                            labelCol={{ span: 6 }}
                            wrapperCol={{ span: 18 }}
                            label="发货地址"
                        >
                            {getFieldDecorator('storeAddressId', {
                            initialValue:list.DefaultAddressId||undefined,
                            rules: [{ required: true, message:'此项为必选项' }],
                            validateTrigger:'onBlur'
                            })(
                                <Select style={{ width: '100%' }}>
                                    {addressList &&

                                    addressList.map(item => {
                                        return <Option value={item.Id} key={item.Id}>{item.Name}</Option>;
                                    })}
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
            </div>
            <Table
                //loading={loading}
                //bordered
                scroll={{ y: list.length>2?146:0 }}
                rowKey={record => record.OrderId}
                dataSource={list}
                columns={columns}
               // rowSelection={rowSelection}
                // onChange={this.handleStandardTableChange}
                 pagination={false}
            />
            <div className="xkd-mt24 xkd-ml16">共{list.length}单</div>
          </Spin>
      </Modal>
    );
	}
}
